{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Markov Chains From Scratch"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Sometimes it pays to go back to basics.  Data science is a massive, complicated field with seemingly endless topics to learn about.  But in our rush to learn about the latest deep learning trends, it's easy to forget that there are simple yet powerful techniques right under our noses.  In this notebook we'll explore one such technique called a Markov chain.  By building one from scratch using nothing but standard Python libraries, we'll see how simplistic they can be while also yielding some cool results.\n",
    "\n",
    "Markov chains are essentially a way to capture the probability of state transitions in a system.  A process can be considered a Markov process if one can make predictions about the future state of the process based soley on its present state (or several of the most recent states for a higher-order Markov process).  In other words, the history doesn't matter beyond a certain point.  There are lots of great explainers out there so I'll leave that for the reader to explore independently ([this one](http://setosa.io/ev/markov-chains/) is my favorite).  It will become clearer as we step through the code, so let's dive in."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For this example we're going to build a language-based Markov chain.  More specifically, we'll read in a corpus of text and identify pairs of words that appear together.  The pairings are sequential such that when a word w1 is followed by a word w2, then we say that the system has a probablistic state transition from w1 to w2.  An example will help.  Consider the phrase \"the brown fox jumped over the lazy dog\".  If we break this down by word pairings, our state transitions would look like this:\n",
    "\n",
    "the: [brown, lazy]<br>\n",
    "brown: [fox]<br>\n",
    "fox: [jumped]<br>\n",
    "over: [the]<br>\n",
    "lazy: [dog]<br>\n",
    "\n",
    "This set of state transitions is called a Markov chain.  With this in hand we can now choose a starting point (i.e. a word in the corpus) and \"walk the chain\" to create a new phrase.  Markov chains built in this manner over large amounts of text can produce surprisingly realistic-sounding phrases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In order to get started we need a corpus of text.  Anything sufficiently large will do, but to really have some fun (and at the risk of bringing politics into the mix) we're going to make Markov chains great again by using [this collection of text from Donald Trump's campain speeches](https://github.com/ryanmcdermott/trump-speeches).  Our first step is to import the text file and parse it into words."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Corpus size: 166259 words.\n"
     ]
    }
   ],
   "source": [
    "import urllib2\n",
    "text = urllib2.urlopen('https://raw.githubusercontent.com/ryanmcdermott/trump-speeches/master/speeches.txt')\n",
    "words = []\n",
    "for line in text:\n",
    "    line = line.decode('utf-8-sig', errors='ignore')\n",
    "    line = line.encode('ascii', errors='ignore')\n",
    "    line = line.replace('\\r', ' ').replace('\\n', ' ')\n",
    "    new_words = line.split(' ')\n",
    "    new_words = [word for word in new_words if word not in ['', ' ']]\n",
    "    words = words + new_words\n",
    "\n",
    "print('Corpus size: {0} words.'.format(len(words)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "I did some clean-up by converting it to ASCII and removing line breaks but that's about it, the rest of the text is just left as it appears in the source file.  Our next step is to build the transition probabilities.  We'll represent our transitions as a dictionary where the keys are the distinct words in the corpus and the value for a given key is a list of words that appear after that key.  To build the chain we just need to iterate through the list of words, add it to the dictionary if it's not already there, and add the word proceeding it to the list of transition words."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Chain size: 13292 distinct words.\n"
     ]
    }
   ],
   "source": [
    "chain = {}\n",
    "n_words = len(words)\n",
    "for i, key in enumerate(words):\n",
    "    if n_words > (i + 1):\n",
    "        word = words[i + 1]\n",
    "        if key not in chain:\n",
    "            chain[key] = [word]\n",
    "        else:\n",
    "            chain[key].append(word)\n",
    "\n",
    "print('Chain size: {0} distinct words.'.format(len(chain)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It may come as a surprise that we're just naively inserting words into the transition list without caring if that word had appeared already or not.  Won't we get duplicates, and isn't that a problem?  Yes we will, and no it's not.  Think of this as a simplistic way of representing the transition probability.  If a word appears multiple times in the list, and we sample from the list randomly during a transition, there's a higher likelihood that we pick that word proportional to the number of times it appeared after the key relative to all the other words in the corpus that appeared after that key."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we've built our Markov chain, we can get to the fun part - using it to generate phrases!  To do this we only need two pieces of information - a starting word, and a phrase length.  We're going to randomly select a starting word from the corpus and make our phrases tweet-length by sampling until our phrase hits 140 characters (assume we're part of the #never280 crowd).  Let's give it a try."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Were not going to run by the 93 million people are, where were starting. New Hampshire.\" I PROMISE. I do so incredible, and be insulted, Chuck.\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "w1 = random.choice(words)\n",
    "tweet = w1\n",
    "\n",
    "while len(tweet) < 140:\n",
    "    w2 = random.choice(chain[w1])\n",
    "    tweet += ' ' + w2\n",
    "    w1 = w2\n",
    "\n",
    "print(tweet)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Not bad!  The limitations of using only one word for context are readily apparent though.  We can improve it by using a 2nd-order Markov chain instead.  This time, instead of using simple word pairings, our \"keys\" will be the set of distinct tuples of words that appear in the text.  Borrowing from the example phrase earlier, a 2nd-order Markov chain for \"the brown fox jumped over the lazy dog\" would look like:\n",
    "\n",
    "(the, brown): [fox]<br>\n",
    "(brown, fox): [jumped]<br>\n",
    "(fox, jumped): [over]<br>\n",
    "(jumped, over): [the]<br>\n",
    "(over, the): [lazy]<br>\n",
    "(the, lazy): [dog]<br>\n",
    "\n",
    "In order to build a 2nd-order chain, we have to make a few modifications to the code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Chain size: 72373 distinct word pairs.\n"
     ]
    }
   ],
   "source": [
    "chain = {}\n",
    "n_words = len(words)\n",
    "for i, key1 in enumerate(words):\n",
    "    if n_words > i + 2:\n",
    "        key2 = words[i + 1]\n",
    "        word = words[i + 2]\n",
    "        if (key1, key2) not in chain:\n",
    "            chain[(key1, key2)] = [word]\n",
    "        else:\n",
    "            chain[(key1, key2)].append(word)\n",
    "\n",
    "print('Chain size: {0} distinct word pairs.'.format(len(chain)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can do a sanity check to make sure it's doing what we expect by choosing a word pair that appears somewhere in the text and then examining the transitions in the chain for that pair of words."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['great',\n",
       " 'great',\n",
       " 'easy.',\n",
       " 'preposterous.',\n",
       " 'important...',\n",
       " 'simple.',\n",
       " 'simple.',\n",
       " 'horrible.',\n",
       " 'out',\n",
       " 'terrible.',\n",
       " 'sad.',\n",
       " 'much',\n",
       " 'can',\n",
       " 'easy.',\n",
       " 'embarrassing',\n",
       " 'astronomical']"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chain[(\"Its\", \"so\")]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks about like what I'd expect.  Next we need to modify the \"tweet\" code to handle the new design."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "there. They saw it. He talks about medical cards. He talks about fixing the VA health care. They want to talk to me from Georgia? \"Dear So and\n"
     ]
    }
   ],
   "source": [
    "r = random.randint(0, len(words) - 1)\n",
    "key = (words[r], words[r + 1])\n",
    "tweet = key[0] + ' ' + key[1]\n",
    "\n",
    "while len(tweet) < 140:\n",
    "    w = random.choice(chain[key])\n",
    "    tweet += ' ' + w\n",
    "    key = (key[1], w)\n",
    "\n",
    "print(tweet)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Better!  Let's turn this into a function that we can call repeatedly to see a few more examples."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def markov_tweet(chain, words):\n",
    "    r = random.randint(0, len(words) - 1)\n",
    "    key = (words[r], words[r + 1])\n",
    "    tweet = key[0] + ' ' + key[1]\n",
    "\n",
    "    while len(tweet) < 140:\n",
    "        w = random.choice(chain[key])\n",
    "        tweet += ' ' + w\n",
    "        key = (key[1], w)\n",
    "\n",
    "    print(tweet + '\\n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "East. But we have a huge subject. Ive been with the Romney campaign. Guys made tens of thousands of people didnt care about the vets in one hour.\n",
      "\n",
      "somebody is going to put American-produced steel back into the sky. It will be the candidate. But I think 11 is a huge problem. And Im on the\n",
      "\n",
      "THAT WE CAN ONLY DREAM ABOUT. THEY HAVE A VERY BIG BEAUTIFUL GATE IN THAT WALL, BIG AND BEAUTIFUL, RIGHT. NO. NO, I DON'T KNOW WHERE THEY HAVE\n",
      "\n",
      "We need to get so sick of me. I didnt want the world my tenant. They buy condos for tens of millions of dollars overseas. And too many executive\n",
      "\n",
      "Wont be as good as you know, started going around and were going to win. Were going to happen. Thank you. SPEECH 8 This is serious rifle. This\n",
      "\n"
     ]
    }
   ],
   "source": [
    "markov_tweet(chain, words)\n",
    "markov_tweet(chain, words)\n",
    "markov_tweet(chain, words)\n",
    "markov_tweet(chain, words)\n",
    "markov_tweet(chain, words)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That's all there is to it!  Incredibly simple yet surprisingly effective.  It's obviously not perfect but it's not complete gibberish either.  If you run it enough times you'll find some combinations that actually sound pretty plausible.  These results could probably be improved significantly with a much more powerful technique like a recurrent neural net, but relative to the effort involved it's hard to beat Markov chains."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
